package {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filters.BlurFilter;
	import flash.filters.ColorMatrixFilter;
	import flash.filters.DisplacementMapFilter;
	import flash.geom.Point;

	[SWF(backgroundColor=0)]
	public class TrailingFire extends Sprite
	{
		public var bmp:Bitmap;
		public var bmd:BitmapData;
		public var perlin:BitmapData;
		public var offset:Array;
		public var seed:Number;
		
		public var blur:BlurFilter = new BlurFilter(10,10,3);
		public var colorFade:ColorMatrixFilter = new ColorMatrixFilter([1,0,0,0,0,
																		0,.75,0,0,0,
																		0,0,1,0,0,
																		0,0,0,.5,0]);
		
		public var fireSource:Sprite;
		
		public function TrailingFire()
		{
			fireSource = new Sprite();
			fireSource.graphics.beginFill(0xFF0000, 1);
			fireSource.graphics.drawCircle(0, 0, 30);
			fireSource.graphics.endFill();
			//this.addChild(fireSource);
			
			bmd = new BitmapData(stage.stageWidth,stage.stageHeight,true,0);
			bmp = new Bitmap(bmd);
			bmp.x = 0;
			bmp.y = 0;
			this.addChild(bmp);
			
			perlin = new BitmapData(stage.stageWidth, stage.stageHeight);
			offset = [new Point(0,0), new Point(0,0), new Point(0,0)];
			seed = Math.floor(Math.random()*1000);
			perlin.perlinNoise(15,  15,  3,  seed,  false, false,  5,  false, offset);
			this.cacheAsBitmap = true;
			
			this.filters = [new DisplacementMapFilter(perlin, new Point(0,0), BitmapDataChannel.BLUE, BitmapDataChannel.RED, 15, -30)];
			
			this.addEventListener(Event.ENTER_FRAME, onEnter);
		}
		
		private function onEnter(e:Event):void
		{
			bmd.applyFilter(bmd,bmd.rect,new Point(0,0), colorFade);
			bmd.draw(this);
			bmd.draw(fireSource);
			bmd.applyFilter(bmd,bmd.rect,new Point(0,0), blur);
			
			fireSource.graphics.clear();
			fireSource.graphics.beginFill(0xFFCC00, 1);
			fireSource.graphics.drawCircle(this.mouseX, this.mouseY,30);
			fireSource.graphics.endFill();
			
			offset[0].x += 1;
			offset[0].y += 2;
			offset[1].x += -1;
			offset[1].y += -1;
			offset[2].x += 2;
			offset[2].y += 1;
			perlin.perlinNoise(15,  15,  3,  seed,  false, false,  5,  false, offset);
			this.filters = [new DisplacementMapFilter(perlin, new Point(0,0), BitmapDataChannel.BLUE, BitmapDataChannel.RED, 15, -30)];
		}
	}
}
